package com.zlcdgroup.delegates

import com.zlcdg.study.kotlin.com.zlcdgroup.delegates.ValidatorUtil
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 *委托读写参数校验的实现类
 *@author pei
 *@date 2024/9/26 17:15
 *
 */
class ZlcdDelegatesNotNullVar<T : Any>(
    private val params: DelegatesValidator.DelegatesValidatorBuilderParams,
) : ReadWriteProperty<Any?, T> {
    private var value: T? = null

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        val newValue = value ?: throw AppException(params.nullErrorMsg)
        for (key in params.conditionMap.keys) {
            val errorMsg = params.conditionMap[key]!!
            when (key) {
                ConditionType.STRING_NOT_BLANK -> {
                    ValidatorUtil.notBlank(newValue, errorMsg)
                }

                ConditionType.STRING_SIZE_RANGE -> {
                    ValidatorUtil.sizeRange(newValue, params.minLen, params.maxLen, errorMsg)
                }

                ConditionType.NUMBER_RANGE -> {
                    ValidatorUtil.numberRang(newValue, params.minValue, params.maxValue, errorMsg)
                }

                ConditionType.STRING_EMAIL -> {
                    ValidatorUtil.email(newValue, errorMsg)
                }

                ConditionType.STRING_IDCARD -> {
                    ValidatorUtil.idCard(newValue, errorMsg)
                }

                ConditionType.STRING_MOBILE_PHONE -> {
                    ValidatorUtil.mobilePhone(newValue, errorMsg)
                }

                ConditionType.STRING_INSET -> {
                    ValidatorUtil.stringInSet(newValue, params.stringDataSet, errorMsg)
                }

                ConditionType.NUMBER_INSET -> {
                    ValidatorUtil.numberInSet(newValue, params.numberDataSet, errorMsg)
                }

                ConditionType.STRING_START -> {
                    ValidatorUtil.stringStart(newValue, params.startStr, errorMsg)
                }

                ConditionType.STRING_END -> {
                    ValidatorUtil.stringEnd(newValue, params.endStr, errorMsg)
                }

                ConditionType.STRING_CONTAINS -> {
                    ValidatorUtil.stringContains(newValue, params.containStr, errorMsg)
                }

                ConditionType.STRING_DATE -> {
                    ValidatorUtil.date(newValue, params.dateFormat, errorMsg)
                }

                ConditionType.STRING_XSS -> {
                    ValidatorUtil.xss(newValue, errorMsg)
                }
            }
        }
        return newValue
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = value

    }

    override fun toString(): String = "kotlin托管校验对象！"

}

